﻿using System;
using System.IO;
using AurelienRibon.Core.Options;
using CodeIn.Core;
using CodeIn.Core.Modules;

namespace CodeIn.Modules.Core {
	public class Options : BaseModule {
		public static readonly string OPT_ENV_STARTUPDIRECTORY = "Environment.StartupDirectory";
		public static readonly string OPT_ENV_WORKINGDIRECTORY = "Environment.WorkingDirectory";

		protected override void InitializeOverride() {
			var startupDirectoryOpt = new Option(
				OPT_ENV_STARTUPDIRECTORY,
				Environment.CurrentDirectory,
				false,
				null,
				(val, old) => {
					if (Directory.Exists(val))
						return new DirectoryInfo(val).FullName;
					return old;
				});

			var workingDirectoryOpt = new Option(
				OPT_ENV_WORKINGDIRECTORY,
				Environment.CurrentDirectory,
				false,
				(val) => { return Environment.CurrentDirectory; },
				(val, old) => {
					DirectoryInfo dirInfo = new DirectoryInfo(val);
					if (dirInfo.Exists) {
						Environment.CurrentDirectory = dirInfo.FullName;
						return dirInfo.FullName;
					}
					return old;
				});

			OptionManager.Instance.RegisterOption(startupDirectoryOpt);
			OptionManager.Instance.RegisterOption(workingDirectoryOpt);
		}

		protected override bool CanExecuteOverride(string[] args) {
			return true;
		}

		protected override void ExecuteOverride(string[] args) {
			var wd = OptionManager.Instance.GetOptionFromName(OPT_ENV_WORKINGDIRECTORY);
			var sd = OptionManager.Instance.GetOptionFromName(OPT_ENV_STARTUPDIRECTORY);
			wd.Value = sd.Value;
		}
	}
}
